<?php
abstract class Protox_Controller_Action extends Zend_Controller_Action
{

	/**
	 * Inicializa o objeto View
	 *
	 * @return Zend_View
	 */
	public function init()
	{
		$this->_initView();
	}

	/**
	 * Recupera o objeto View
	 *
	 * @return Protox_View
	 */
	protected function _initView()
	{
		$view = new Protox_View($this->view);
		$this->view = $view->init();
	}

	/**
	 * Função executada antes do controller ser executado
	 * Para controller de error e requisições ajax desabilita o layout
	 * Inclui uma variavel baseUrl para javascript
	 */
	public function preDispatch()
	{
		if ($this->_request->isXmlHttpRequest() ||
		$this->_request->getModuleName()=="error" ||
		isset($_GET['ajax']))
		{
			$this->_helper->layout()->disableLayout();
		}

		$script = 'var baseUrl = "' . $this->view->baseUrl() . '";' . PHP_EOL;

		$this->view->headScript()->prependScript($script, $type = 'text/javascript', $attrs = array());
	}


	/**
	 * Helper para redirecionar para um action ou controller especifico para um modulo
	 *
	 * @param string  $controller / $url
	 * @param string  $action
	 * @param string  $module
	 * @param array   $params
	 * @param string  $route
	 * @param boolean $reset
	 */
	public function redirect($controller = 'index', $action = 'index', $module = 'default', $params = array(), $route = null, $reset = true )
	{
		$this->_redirect = $this->_helper->getHelper('Redirector');

		$current_controller = $this->_getParam('controller');
		$current_action     = $this->_getParam('action');
		$current_module     = $this->_getParam('module');

		if ($current_controller == $controller &&
		$current_action == $action &&
		$current_module == $module)
		{
			return TRUE;
		}

		if (strstr($controller, 'http'))
		{
			return $this->_redirect($controller, array('code' => 301));
		}

		if ($route !== null)
		{
			$params = array_merge(array(
                'action'     => $action,
                'controller' => $controller,
                'module'     => null), $params);

			return $this->_redirect->setCode(301)
			->setExit(true)
			->gotoRoute($params, $route, $reset);
		}

		return $this->_redirect->setCode(301)
		->setExit(true)
		->gotoSimpleAndExit($action,$controller,$module,$params);
	}
	
}

